package com.api_getway.api_getway.config.filter;

import com.example.commons.utils.JWTUtil;
import com.example.commons.utils.JinZhiException;
import com.google.gson.JsonObject;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 全局Filter，统一处理登录与外部不允许访问的服务
 * </p>
 *
 * @author qy
 * @since 2019-11-21
 */
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        //这里是设置拦截信息 请求路径中保护该路径九需要判断是否登录
       //boolean b= antPathMatcher.match("/jinZhiConsumer/**", path);
         //api接口，校验用户必须登录
        boolean b= antPathMatcher.match("/jinZhiIndex/jzmy/home/showMsgState/**", path);
        if(b){
            //首页获取信息直接放行
            return chain.filter(exchange);//2 全部放行
        }

        if(filterList(path)) {
                List<String> tokenList = request.getHeaders().get("Blade-Auth");
            if(null == tokenList||tokenList.size()==0) {
                ServerHttpResponse response = exchange.getResponse();
                return out(response);
            } else {
                //校验用户的token
                 JWTUtil.jzverify(tokenList.get(0));

            }
        }
        //内部服务接口，不允许外部访问/特殊安全接口
//        if(antPathMatcher.match("/**/inner/**", path)) {
//            ServerHttpResponse response = exchange.getResponse();
//            return out(response);
//        }
        return chain.filter(exchange);//2 全部放行
    }

    public boolean filterList(String path){
        boolean b=false;
        List<String> list=new ArrayList<>();
        //这里通过list可以配置多个拦截器规则
        list.add("/jinZhiConsumer1/**");
/**
 * /jinZhiIndex/jzApi/sheet/info
 * /jinZhiIndex/jzApi/sheet/userQuestionsInfo
 * /jinZhiIndex/jzApi/sheet/infoPractice
 * /jinZhiIndex/jzApi/sheet/selAnswerSheet
 * /jinZhiIndex/jzApi/examinations/appletsSelExamination
 */
        list.add("/jinZhiConsumer1/**");

        list.add("/jinZhiConsumer1/**");
        list.add("/jinZhiIndex/jzApi/sheet/info/**");
        list.add("/jinZhiIndex/jzApi/sheet/userQuestionsInfo/**");
        list.add("/jinZhiIndex/brand/**");
        list.add("/jinZhiIndex/jzApi/sheet/infoPractice/**");
        list.add("/jinZhiIndex/jzApi/examinations/appletsSelExamination/**");
        list.add("/jinZhiIndex/jzApi/sheet/selAnswerSheet/**");
        list.add("/jinZhiIndex/jzApi/examinations/selTrainExaminationPaper/**");

       // list.add("/jinZhiIndex/banners/**");
        for(String li:list){
            b= antPathMatcher.match(li, path);
            if(b){
                return b;
            }
        }

        return b;
    }

    @Override
    public int getOrder() {
        return 0;
    }

    private Mono<Void> out(ServerHttpResponse response) {
        JsonObject message = new JsonObject();
        message.addProperty("success", false);
        message.addProperty("code", 28004);
        message.addProperty("data", "验证失败");
        byte[] bits = message.toString().getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        //response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }

}
